﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OAuthClient.Models;
using OAuthClient.Server;
using System.Diagnostics;
using System.Security.Claims;

namespace OAuthClient.Controllers
{
    public class AuthController : Controller {

        public IActionResult Callback() {

            // 从回调URL中提取授权码和状态参数
            var code = Request.Query["code"];
            var state = Request.Query["state"];
            return View();
        }


    }
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            //string authority = "https://localhost:5000";

            //string clientId = "liya00";
            //string clientSecret = "123";
            //string responseType = Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectResponseType.Code;
            //string redirect_uri= "https://localhost:5001/signin-oidc";

            //if (!User.Identity.IsAuthenticated) // 检查用户是否已经登录
            //{
            //    // 构建重定向URL，包括授权类型、回调URL和API资源等参数
            //    var redirectUrl = $"{authority}/oauth/authorize" +
            //        $"?response_type={responseType}" +
            //        $"&client_id={clientId}" +  
            //        $"&redirect_uri={System.Web.HttpUtility.UrlEncode(redirect_uri)}" +
            //        $"&scope=openid+profile+email" +
            //        $"&state=your-state";
            //    return Redirect(redirectUrl); // 重定向到OAuth 2.0授权中心
            //}
            return View();
        }

        [HttpGet("signin-oidc")]
        public async Task<IActionResult> SignInCallback()
        {
            // 从回调URL中提取授权码和状态参数
            var code = Request.Query["code"];
            var state = Request.Query["state"];
            // 使用授权码向Identity Server请求访问令牌和ID令牌
            var tokenClient = new HttpClient();
            var tokenRequestData = new Dictionary<string, string>
        {
            { "grant_type", "authorization_code" },
            { "code", code },
            { "redirect_uri", "https://your-app-domain/signin-oidc" },
            { "client_id", "your-client-id" },
            { "client_secret", "your-client-secret" }
        };
            var tokenResponse = await tokenClient.PostAsync("https://your-identity-server-url/connect/token", new FormUrlEncodedContent(tokenRequestData));
            var tokenResponseContent = await tokenResponse.Content.ReadAsStringAsync();
            // 解析访问令牌和ID令牌，并进行相应的处理
            // ...
            // 返回响应或重定向到其他页面
            return View();
        }
        [Authorize]
        public IActionResult Privacy()
        {
        var claims=    HttpContext.User.Claims.ToList();

            ViewBag.claims = claims;
            return View();
        }

        //[HttpGet("auth/callback")]
        //public IActionResult callback(string code)
        //{
           
        //    return View();
        //}
        public async Task<IActionResult> info(AuthClient client)
        {
            var name = HttpContext.User.FindFirstValue("name");
          string info=await  client.GetInfo(name);
            ViewBag.info = info;
            return View();
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
